package org.pentaho.streaming.autotask;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.*;
import org.pentaho.di.core.row.value.ValueMetaFactory;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.streaming.common.BaseStreamStepMeta;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.trans.step.BaseStreamingDialog;

import static java.util.Arrays.stream;

@SuppressWarnings("unused")
public class AutoTaskConsumerDialog extends BaseStreamingDialog implements StepDialogInterface {
    private static Class<?> PKG = AutoTaskConsumerMeta.class; // for i18n

    private AutoTaskConsumerMeta taskMeta;
    private TableView fieldsTable;

    private final Point startingDimensions = new Point(527, 676);

    public AutoTaskConsumerDialog(Shell parent, Object in, TransMeta tr, String sname) {
        super(parent, in, tr, sname);
        taskMeta = (AutoTaskConsumerMeta) in;
    }

    @Override
    protected void getData() {
        super.getData();
        populateTopicsData();
    }

    private void populateTopicsData() {
        int rowIndex = 0;
    }

    @Override
    protected String getDialogTitle() {
        return BaseMessages.getString(PKG, "AutoTaskConsumerDialog.Shell.Title");
    }

    @Override
    public void setSize() {
        setSize(shell);  // sets shell location and preferred size
        shell.setMinimumSize(startingDimensions);
        shell.setSize(startingDimensions); // force initial size
    }

    @Override
    protected void buildSetup(Composite wSetupComp) {
        props.setLook(wSetupComp);
        FormLayout setupLayout = new FormLayout();
        setupLayout.marginHeight = 15;
        setupLayout.marginWidth = 15;
        wSetupComp.setLayout(setupLayout);

        Label wlNoConfiguration = new Label(wSetupComp, SWT.LEFT);
        props.setLook(wlNoConfiguration);
        wlNoConfiguration.setText(BaseMessages.getString(PKG, "AutoTaskConsumerDialog.NoConfiguration"));
        FormData fdlConnection = new FormData();
        fdlConnection.left = new FormAttachment(0, 0);
        fdlConnection.top = new FormAttachment(0, 0);
        fdlConnection.right = new FormAttachment(50, 0);
        wlNoConfiguration.setLayoutData(fdlConnection);
    }

    @Override
    protected void createAdditionalTabs() {
        buildFieldsTab();

        // 设置按钮可用性
        wBatchSize.setEnabled(false);
        Class<? extends AutoTaskConsumerDialog> c = this.getClass();

//        PDI版本 > 9
//        try {
//            TextVar _wPrefetchCount = (TextVar) c.getSuperclass().getDeclaredField("wPrefetchCount").get(this);
//            _wPrefetchCount.setEnabled(false);
//        } catch (NoSuchFieldException | IllegalAccessException e) {
//            e.printStackTrace();
//        }
    }

    /**
     * 获取输出字段
     */
    @Override
    protected String[] getFieldNames() {
        return stream(fieldsTable.getTable().getItems()).map(row -> row.getText(2)).toArray(String[]::new);
    }

    /**
     * 获取输出字段类型
     */
    @Override
    protected int[] getFieldTypes() {
        return stream(fieldsTable.getTable().getItems())
                .mapToInt(row -> ValueMetaFactory.getIdForValueMeta(row.getText(3))).toArray();
    }

    private void buildFieldsTab() {
        CTabItem wFieldsTab = new CTabItem(wTabFolder, SWT.NONE, 3);
        wFieldsTab.setText(BaseMessages.getString(PKG, "AutoTaskConsumerDialog.FieldsTab"));

        Composite wFieldsComp = new Composite(wTabFolder, SWT.NONE);
        props.setLook(wFieldsComp);
        FormLayout fieldsLayout = new FormLayout();
        fieldsLayout.marginHeight = 15;
        fieldsLayout.marginWidth = 15;
        wFieldsComp.setLayout(fieldsLayout);

        FormData fieldsFormData = new FormData();
        fieldsFormData.left = new FormAttachment(0, 0);
        fieldsFormData.top = new FormAttachment(wFieldsComp, 0);
        fieldsFormData.right = new FormAttachment(100, 0);
        fieldsFormData.bottom = new FormAttachment(100, 0);
        wFieldsComp.setLayoutData(fieldsFormData);

        buildFieldTable(wFieldsComp, wFieldsComp);

        wFieldsComp.layout();
        wFieldsTab.setControl(wFieldsComp);
    }

    private void buildFieldTable(Composite parentWidget, Control relativePosition) {
        ColumnInfo[] columns = getFieldColumns();

        fieldsTable = new TableView(
                transMeta,
                parentWidget,
                SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI,
                columns,
                1,
                true,
                lsMod,
                props,
                false
        );

        fieldsTable.setSortable(false);
        fieldsTable.getTable().addListener(SWT.Resize, event -> {
            Table table = (Table) event.widget;
            table.getColumn(1).setWidth(147);
            table.getColumn(2).setWidth(147);
            table.getColumn(3).setWidth(147);
        });

        populateFieldData();

        FormData fdData = new FormData();
        fdData.left = new FormAttachment(0, 0);
        fdData.top = new FormAttachment(relativePosition, 5);
        fdData.right = new FormAttachment(100, 0);

        // resize the columns to fit the data in them
        stream(fieldsTable.getTable().getColumns()).forEach(column -> {
            if (column.getWidth() > 0) {
                // don't pack anything with a 0 width, it will resize it to make it visible (like the index column)
                column.setWidth(120);
            }
        });

        // don't let any rows get deleted or added (this does not affect the read-only state of the cells)
        fieldsTable.setReadonly(true);
        fieldsTable.setLayoutData(fdData);
    }

    private void populateFieldData() {
        TableItem messageItem = fieldsTable.getTable().getItem(0);
        messageItem.setText(1, "dateAt");
        messageItem.setText(2, taskMeta.getDateAt());
        messageItem.setText(3, "String");
    }

    private ColumnInfo[] getFieldColumns() {
        ColumnInfo referenceName = new ColumnInfo(BaseMessages.getString(PKG, "AutoTaskConsumerDialog.Column.Ref"),
                ColumnInfo.COLUMN_TYPE_TEXT, false, true);
        ColumnInfo name = new ColumnInfo(BaseMessages.getString(PKG, "AutoTaskConsumerDialog.Column.Name"),
                ColumnInfo.COLUMN_TYPE_TEXT, false, false);
        ColumnInfo type = new ColumnInfo(BaseMessages.getString(PKG, "AutoTaskConsumerDialog.Column.Type"),
                ColumnInfo.COLUMN_TYPE_TEXT, false, true);
        return new ColumnInfo[]{referenceName, name, type};
    }

    @Override
    protected void additionalOks(BaseStreamStepMeta meta) {
        taskMeta.setDateAt(fieldsTable.getTable().getItem(0).getText(2));
        super.additionalOks(meta);
    }
}
